//
//  FactoryMapViewController.m
//  MagictoHire
//
//  Created by 锋 on 2017/12/21.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "FactoryMapViewController.h"
#import "CustomSearchBar.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

@interface FactoryMapViewController ()<UITextFieldDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, AMapSearchDelegate, CLLocationManagerDelegate, MAMapViewDelegate>
{
    UITextField *_addressTextField; // 输入框
    MAMapView *_mapView;
    CGFloat keyboardHight;
    NSString *addressStr;
    CLLocationManager *_locationManager;
    CLLocationCoordinate2D addressCoordinate;
    CLLocationCoordinate2D mapCenterCoordinate;
}
@property (nonatomic, strong) CustomSearchBar *searchBar;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) UITableView *addressTableView;
@property (nonatomic, strong) NSMutableArray *filterArray;
@property (nonatomic, strong) NSMutableArray *selectArr;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, assign) NSInteger searchType;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
//@property (nonatomic, strong) NSMutableArray<id <QAnnotation> > *annotations;
@end

@implementation FactoryMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    addressStr = @"";
    self.filterArray = @[].mutableCopy;
    self.selectArr = @[].mutableCopy;
    [self creatUI];
    [self setupAddressTableView];
    [self initMapView];
    [self initializeLocationService];
    // Do any additional setup after loading the view.
}

- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    addressCoordinate = newLocation.coordinate;
    [self searchCoordinate];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)creatUI
{
    [self addSearchBar];
    
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(ensureLocation)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightBtn;
    UITapGestureRecognizer *hideKeyBoard = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoardAction)];
    hideKeyBoard.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:hideKeyBoard];
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
}

// MARK:自定义searchbar
- (void)addSearchBar {
    
    _searchBar = [self addSearchBarWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 2 * 55 - 2 * 15, 44)];
    UIView *wrapView = [[UIView alloc] initWithFrame:_searchBar.frame];
    [wrapView addSubview:_searchBar];
    self.navigationItem.titleView = wrapView;
}
- (CustomSearchBar *)addSearchBarWithFrame:(CGRect)frame {
    
    self.definesPresentationContext = YES;
    
    CustomSearchBar *searchBar = [[CustomSearchBar alloc]initWithFrame:frame];
    searchBar.delegate = self;
    [searchBar setShowsCancelButton:NO];
    //    [searchBar setTintColor:[UIColor lightGrayColor]];   //设置光标颜色
    
    if (self.isChangeSearchBarFrame) {
        
        CGFloat height = searchBar.bounds.size.height;
        CGFloat top = (height - 20.0) / 2.0;
        CGFloat bottom = top;
        
        searchBar.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    }
    return searchBar;
}

- (void)hideKeyBoardAction {
    [self.searchBar resignFirstResponder];
}

- (void)initMapView
{
    [AMapServices sharedServices].apiKey = GAODEKEY;
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (SCREEN_HEIGHT-SCREER_HeiX)/2)];
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    _mapView.zoomLevel = 16.5;
    _mapView.delegate = self;
    mapCenterCoordinate = _mapView.centerCoordinate;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    UIImageView *locationImageView = [ZCControl createImageViewWithFrame:CGRectMake(0, 0, 30, 30) ImageName:@"datouz"];
    locationImageView.center = CGPointMake(_mapView.center.x, _mapView.center.y-30);
    [_mapView addSubview:locationImageView];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
}

- (void)setupAddressTableView {
    self.addressTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, (SCREEN_HEIGHT-SCREER_HeiX)/2-STA_NAV_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-(SCREEN_HEIGHT-SCREER_HeiX)/2-SCREER_HeiX) style:UITableViewStyleGrouped];
    _addressTableView.delegate = self;
    _addressTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _addressTableView.tableHeaderView = view;
    _addressTableView.tableFooterView = view;
    _addressTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_addressTableView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _filterArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    
    UIButton *selectBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-30, 0, 30, 44) ImageName:@"" Target:self Action:@selector(onClickSelectBtn) Title:nil Font:10];
    selectBtn.tag = indexPath.row+10;
    [selectBtn setImage:[UIImage imageNamed:@"xuanze"] forState:UIControlStateSelected];
    [selectBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [cell.contentView addSubview:selectBtn];
    selectBtn.selected = [_selectArr[indexPath.row] boolValue];
    
    AMapPOI *poi = _filterArray[indexPath.row];
    cell.textLabel.text = poi.name;
    cell.detailTextLabel.text = poi.address;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    _selectArr[indexPath.row] = @(YES);
    for (int i = 0; i < _selectArr.count; i++) {
        if (indexPath.row != i) {
            _selectArr[i] = @(NO);
        }
    }
    AMapPOI *poi = _filterArray[indexPath.row];
    CLLocationCoordinate2D selectCoordinate;
    selectCoordinate.latitude = poi.location.latitude;
    selectCoordinate.longitude = poi.location.longitude;
    [_mapView setCenterCoordinate:selectCoordinate animated:YES];
    [_addressTableView reloadData];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)onClickSelectBtn {
    
}

- (void)ensureLocation {
    if (LocationServiceOFF) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"定位服务未开启" message:@"无法获取你的位置信息，请在iPhone的\"设置-隐私\"选项中，允许Gluue使用定位服务" preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }

    NSInteger index = 0;
    BOOL isSelectAddress = NO;
    for (int i = 0; i < _selectArr.count; i++) {
        BOOL selectStatus = [_selectArr[i] boolValue];
        if (selectStatus) {
            index = i;
            isSelectAddress = YES;
        }
    }
    if (!isSelectAddress) {
        [LTools showMBProgressWithText:@"请选择定位地址" addToView:self.view];
        return;
    }
    AMapPOI *poi = _filterArray[index];
    CLLocationCoordinate2D poiCoordinate;
    poiCoordinate.latitude = poi.location.latitude;
    poiCoordinate.longitude = poi.location.longitude;
    if (_searchType==1) {
        NSString *str = [NSString stringWithFormat:@"%@%@", addressStr, poi.name];
        self.mapBlock(poiCoordinate, str);
    } else {
        NSString *str = [NSString stringWithFormat:@"%@%@%@%@", poi.province, poi.city, poi.district, poi.name];
        self.mapBlock(poiCoordinate, str);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchCoordinate {
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
//    [LTools cache:weakSelf.userModel.lat ForKey:@"userlat"];
//    [LTools cache:weakSelf.userModel.lng ForKey:@"userlng"];
//    double lat = [[LTools cacheForKey:@"userlat"] doubleValue];
//    double lng = [[LTools cacheForKey:@"userlng"] doubleValue];
    regeo.location = [AMapGeoPoint locationWithLatitude:addressCoordinate.latitude longitude:addressCoordinate.longitude];
    regeo.requireExtension = YES;
    [self.search AMapReGoecodeSearch:regeo];
}

- (void)searchMoveCoordinate {
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:_mapView.centerCoordinate.latitude longitude:_mapView.centerCoordinate.longitude];
    regeo.requireExtension = YES;
    [self.search AMapReGoecodeSearch:regeo];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if ([searchText isEqualToString:@""]) {
        [self searchCoordinate];
    } else {
//        QMSSuggestionSearchOption *sugSearchOption = [[QMSSuggestionSearchOption alloc] init];
//        [sugSearchOption setKeyword:searchText];
        //    //设置此参数会限制检索城市
        //    [sugSearchOption setRegion:@"北京"];
        //    //此接口同样支持检索分类
        //    [sugSearchOption setFilterByCategories:@"公交站", nil];
//        [self.searcher searchWithSuggestionSearchOption:sugSearchOption];
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        request.keywords = searchText;
        request.requireExtension = YES;
        [self.search AMapPOIKeywordsSearch:request];
    }
}

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        //解析response获取地址描述，具体解析见 Demo
        
        _searchType = 1;
        [_filterArray removeAllObjects];
        [_selectArr removeAllObjects];
        addressStr = [NSString stringWithFormat:@"%@%@%@", response.regeocode.addressComponent.province, response.regeocode.addressComponent.city, response.regeocode.addressComponent.district];
        for (int i = 0; i < response.regeocode.pois.count; i++) {
            AMapPOI *poi = response.regeocode.pois[i];
            [_filterArray addObject:poi];
            [_selectArr addObject:@(NO)];
        }
        [_addressTableView reloadData];
    }
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    _searchType = 2;
    [_filterArray removeAllObjects];
    [_selectArr removeAllObjects];
    for (int i = 0; i < response.pois.count; i++) {
        AMapPOI *poi = response.pois[i];
        [_filterArray addObject:poi];
        [_selectArr addObject:@(NO)];
    }
    [_addressTableView reloadData];
    //解析response获取POI信息，具体解析见 Demo
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
    if (wasUserAction) {
        if (_mapView.centerCoordinate.longitude != mapCenterCoordinate.longitude || _mapView.centerCoordinate.latitude != mapCenterCoordinate.latitude) {
            [self searchMoveCoordinate];
            mapCenterCoordinate = _mapView.centerCoordinate;
        }
    }
}



//关键字的补完与提示回调接口
//- (void)searchWithSuggestionSearchOption:(QMSSuggestionSearchOption *)
//suggestionSearchOption didReceiveResult:(QMSSuggestionResult *)suggestionSearchResult {
//    _searchType = 2;
//    [_filterArray removeAllObjects];
//    [_selectArr removeAllObjects];
//    for (int i = 0; i < suggestionSearchResult.dataArray.count; i++) {
//        QMSSuggestionPoiData *poi = suggestionSearchResult.dataArray[i];
//        [_filterArray addObject:poi];
//        [_selectArr addObject:@(NO)];
//    }
//    [_addressTableView reloadData];
//}

//- (void)searchWithReverseGeoCodeSearchOption:(QMSReverseGeoCodeSearchOption *)
//reverseGeoCodeSearchOption didReceiveResult:(QMSReverseGeoCodeSearchResult *)
//reverseGeoCodeSearchResult {
//    _searchType = 1;
//    [_filterArray removeAllObjects];
//    [_selectArr removeAllObjects];
//    for (int i = 0; i < reverseGeoCodeSearchResult.poisArray.count; i++) {
//        QMSSuggestionPoiData *poi = reverseGeoCodeSearchResult.poisArray[i];
//        [_filterArray addObject:poi];
//        [_selectArr addObject:@(NO)];
//    }
//    [_addressTableView reloadData];
//}

//- (void)onClickMyLocationBtn {
//    _mapView.showsUserLocation = YES;
//    _mapView.userTrackingMode = QUserTrackingModeFollow;
//    [self searchCoordinate];
//}

////<QMapViewDelegate >中的定位回调函数
//- (void)mapViewWillStartLocatingUser:(QMapView *)mapView
//{
//    NSLog(@"%s", __FUNCTION__);
//}
//
//- (void)mapViewDidStopLocatingUser:(QMapView *)mapView
//{
//    NSLog(@"%s", __FUNCTION__);
//
//}

/**
 * @brief 用户位置更新后，会调用此函数
 * @param mapView 地图View
 * @param userLocation 新的用户位置
 * @param fromHeading 是否为heading 变化触发，如果为location变化触发,则为NO
 */
//- (void)mapView:(QMapView *)mapView didUpdateUserLocation:(QUserLocation *)userLocation fromHeading:(BOOL)fromHeading
//{
//    NSLog(@"%s fromHeading = %d, location = %@, heading = %@", __FUNCTION__, fromHeading, userLocation.location, userLocation.heading);
//    if (_mapView.centerCoordinate.latitude != _coordinate.latitude || _mapView.centerCoordinate.longitude != _coordinate.longitude) {
//        if (_searchType == 1) {
//            [self searchCoordinate];
//        }
//    }
//    _coordinate = _mapView.centerCoordinate;
//}

/**
 * @brief  定位失败后，会调用此函数
 * @param mapView 地图View
 * @param error 错误号，参考CLError.h中定义的错误号
 */
//- (void)mapView:(QMapView *)mapView didFailToLocateUserWithError:(NSError *)error
//{
//    NSLog(@"%s error = %@", __FUNCTION__, error);
//}

/**
 * @brief 定位时的userTrackingMode 改变时delegate调用此函数
 *  @param mapView 地图View
 *  @param mode QMUserTrackingMode
 *  @param animated 是否有动画
 */
//- (void)mapView:(QMapView *)mapView didChangeUserTrackingMode:(QUserTrackingMode)mode animated:(BOOL)animated
//{
//    NSLog(@"%s mode = %d, animated = %d", __FUNCTION__, mode, animated);
//
//}

//- (void)searchCoordinate {
//    QMSReverseGeoCodeSearchOption *option = [[QMSReverseGeoCodeSearchOption alloc] init];
//    option.location = [NSString stringWithFormat:@"%lf,%lf", _mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude];
//    //返回坐标点附近poi列表
//    [option setGet_poi:YES];
//    [self.searcher searchWithReverseGeoCodeSearchOption:option];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
